using System;
using System.IO;

namespace ID3Lib
{
	/// <summary>
	/// Manage MP3 file ID3v2 tags.
	/// </summary>
	public class MP3File
	{

		/// <summary>
		/// Read the ID3v2 tag model.
		/// </summary>
		/// <param name="file">File location</param>
		public TagModel Read(string file)
		{
			Stream stream = File.Open(file,FileMode.Open,FileAccess.Read,FileShare.Read);
			TagManager frameManager = new TagManager();
			TagModel tagModel = null;
			try
			{
				tagModel = frameManager.Deserialize(stream);
			}
			finally
			{
				stream.Close();
			}
			return tagModel;
		}

		/// <summary>
		/// Write the tag model to the file.
		/// </summary>
		/// <param name="file">File location were tag will be saved</param>
		/// <param name="tagModel">Tag model beeing saved</param>
		public void Write(string file, TagModel tagModel)
		{
			Stream stream = File.Open(file,FileMode.Open,FileAccess.ReadWrite,FileShare.Read);
							
			int tagSize;
			//Padding and foter can't exist at the same time, I prefer padding over footer.
			//The footer is useful when the tag won't be edited often.
			if(tagModel.Header.Padding == true) 
			{
				tagModel.Header.Footer = false;
			}
			
			if(tagModel.Header.Footer == true)
			{
				// Insert the tag size and header size twice for the hader and footer. 
				tagSize = tagModel.Header.TagSize + tagModel.Header.HeaderSize*2; 
			}
			else
			{
				// Inset the tag size and the header size.
				tagSize = tagModel.Header.TagSize + tagModel.Header.HeaderSize;
			}
			stream.Seek(tagSize,SeekOrigin.Begin);
			MemoryStream memoryStream = new MemoryStream();
			// serialize the frames only first to get the frames real size
			TagManager tagManager = new TagManager();
			tagManager.Serialize(tagModel,memoryStream);
			
			// 
			if(memoryStream.Length > tagSize)
			{

			}
			
			//FileStream writeStream = File.Open(@"c:\Test.mp3",FileMode.Create,FileAccess.ReadWrite,FileShare.Read);
			//frameManager.Serialize(tagModel,writeStream);

			//Copy mp3 stream
		/*	const int size = 4096;
			byte[] bytes = new byte[4096];
			int numBytes;
			while((numBytes = stream.Read(bytes, 0, size)) > 0)
				writeStream.Write(bytes, 0, numBytes);
			writeStream.Close();*/
		}
	}
}
